"""
Description :  
Author :       songtao
date：         2023/10/11
"""
from typing import Union, List
from elasticsearch.exceptions import NotFoundError
from abc import ABCMeta, abstractmethod
from pydantic import BaseModel, Field


class UserParam(BaseModel):
    """
    模型的用户自定义配置
    """
    type_id: int
    region_code: str
    scope: str = Field(comment="配置所属于域名", default="air")
    data: str = Field(comment="用户自定义配置的 json 字符串")


class UserParamQuery(BaseModel):
    type_id: str = ""
    region_code: str = ""
    scope: str = Field(comment="配置所属于域名", default="air")


class IUserParamRepo(metaclass=ABCMeta):
    def __init__(self, **kwargs):
        pass

    @staticmethod
    def get_user_param_db(source):
        m = {
            'es': UserParamEs,
            'hive': UserParamHive,
            'local': UserParamLocal
        }
        return m[source]

    @abstractmethod
    def get_user_param(self, table, param: UserParamQuery):
        """
        :param table: 索引名
        :param param:
        :return: 获取用户自定义配置
        """

    @abstractmethod
    def save_user_param(self, table, data: List[Union[UserParam, dict]]):
        """
        :param table: 索引名
        :param data: 数据
        :return: 保存用户自定义配置
        """


class UserParamLocal(IUserParamRepo):

    def get_user_param(self, table, param: UserParamQuery):
        pass

    def save_user_param(self, table, data: List[Union[UserParam, dict]]):
        pass


class UserParamHive(IUserParamRepo):
    def get_user_param(self, table, param: UserParamQuery):
        pass

    def save_user_param(self, table, data: List[Union[UserParam, dict]]):
        pass


class UserParamEs(IUserParamRepo):
    def __init__(self, **kwargs):
        """
        :param es_conn:
        """
        super().__init__(**kwargs)
        self.es = kwargs.get("es")

    def get_user_param(self, table, param: UserParamQuery):

        filter = []
        if param.type_id:
            filter.append({"term": {"type_id": param.type_id}})
        if param.region_code:
            filter.append({"term": {"region_code": param.region_code}})
        if param.scope:
            filter.append({"term": {"scope": param.scope}})
        query = {"query": {"bool": {"must": filter}}}
        try:
            df_param = self.es.query_by_scroll(table, body=query)
            return df_param
        except NotFoundError:
            pass
        return None

    def save_user_param(self, table, data: List[Union[UserParam, dict]]):
        """
        :return: 保存用户自定义配置
        """
        actions = []
        for i in data:
            action = {
                "_op_type": 'index',
                "_index": table,
                "_id": f"air-{i['region_code']}-{i['type_id']}",
                "_source": i
            }
            actions.append(action)
        self.es.bulk(actions)


USER_DEFINE_PARAM = {
    "base": {
        "comfort_rh": {
            "type": "float",
            "name": "舒适湿度（%）",
            "default": 40
        },
        "year": {
            "type": "int",
            "name": "年份"
        },
        "office_cooling_start_date": {
            "type": "datetime",
            "name": "办公楼宇制冷开始日期"
        },
        "office_cooling_end_date": {
            "type": "datetime",
            "name": "办公楼宇制冷结束日期"
        },
        "office_heating_start_date": {
            "type": "datetime",
            "name": "办公楼宇制热开始日期"
        },
        "office_heating_end_date": {
            "type": "datetime",
            "name": "办公楼宇制热结束日期"
        },
        "uni_winter_break_start_date": {
            "type": "datetime",
            "name": "大学高职寒假开始日期"
        },
        "uni_winter_break_end_date": {
            "type": "datetime",
            "name": "大学高职寒假结束日期"
        },
        "uni_summer_break_start_date": {
            "type": "datetime",
            "name": "大学高职暑假开始日期"
        },
        "uni_summer_break_end_date": {
            "type": "datetime",
            "name": "大学高职暑假结束日期"
        },
        "school_winter_break_start_date": {
            "type": "datetime",
            "name": "中小学寒假开始日期"
        },
        "school_winter_break_end_date": {
            "type": "datetime",
            "name": "中小学寒假结束日期"
        },
        "school_summer_break_start_date": {
            "type": "datetime",
            "name": "中小学暑假开始日期"
        },
        "school_summer_break_end_date": {
            "type": "datetime",
            "name": "中小学暑假结束日期"
        },
        "tourist_high_season_start_date": {
            "type": "datetime",
            "name": "旅游旺季开始日期"
        },
        "tourist_high_season_end_date": {
            "type": "datetime",
            "name": "旅游旺季结束日期"
        }
    },
    "BaseCluster": {
        "comforttemp_H": {
            "type": "float",
            "name": "舒适温度高温（℃）",
            "default": 20
        },
        "comforttemp_L": {
            "type": "float",
            "name": "舒适温度低温（℃）",
            "default": 10
        }
    }
}